<template>
  <div class="achievement-container">

    <van-notice-bar scrollable>
      *根据学校规定，完成以下信息填写才可以提交申请！
    </van-notice-bar>
    <!-- 个人信息卡片 -->
    <div class="user-card">
      <div class="avatar-container">
        <img :src="userInfo.userInfo.userImage" alt="用户头像" class="user-avatar" />
      </div>
      <div class="user-info">
        <div class="info-item">
          <span class="info-label">姓名：</span>
          <span class="info-value">{{ userInfo.userInfo.userName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">工号：</span>
          <span class="info-value">{{ userInfo.userInfo.userNumber }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">职务：</span>
          <span class="info-value">
            <template v-if="userInfo.userInfo.userType == 1">领导</template>
            <template v-else-if="userInfo.userInfo.userType == 2">辅导员</template>
            <template v-else-if="userInfo.userInfo.userType == 3">教师</template>
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">部门：</span>
          <span class="info-value">{{ userInfo.userInfo.department }}</span>
        </div>
      </div>
    </div>
    <div class="add_xq">
      <!-- 班级选择器 -->
      <van-field
          v-model="selectedClassDisplay"
          is-link
          readonly
          required
          label="班级列表"
          placeholder="选择班级"
          @click="showClassPicker = true"
          style="margin: 15px 0 15px 0"
      />
      <van-popup v-model:show="showClassPicker" destroy-on-close round position="bottom">
        <van-picker
            :columns="classColumns"
            @cancel="showClassPicker = false"
            @confirm="onConfirmClass"
        />
      </van-popup>
      <div class="xzq">
        <div class="xzq_left">
          <van-field
              v-model="date_value"
              is-link
              readonly
              placeholder="选择日期"
              @click="showPicker3 = true; setCurrentDate()"
          />
          <van-popup v-model:show="showPicker3" destroy-on-close round position="bottom">
            <van-date-picker
                v-model="currentDate"
                title="选择日期"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="onConfirmDate"
                @cancel="showPicker3 = false"
            />
          </van-popup>
        </div>
        <div class="xzq_right">
          <van-field
              v-model="time_value"
              is-link
              readonly
              placeholder="选择时间"
              @click="showPicker4 = true; setCurrentTime()"
          />
          <van-popup v-model:show="showPicker4" destroy-on-close round position="bottom">
            <van-time-picker
                v-model="currentTime"
                title="选择时间"
                :formatter="formatter"
                @confirm="onConfirmTime"
                @cancel="showPicker4 = false"
            />
          </van-popup>
        </div>
      </div>

      <!--    教学评价-->
      <van-field
          v-model="jxpj"
          is-link
          readonly
          required
          label="教学评价"
          placeholder="选择等级"
          @click="showPicker1 = true"
          style="margin-top: 15px"
      />
      <van-popup v-model:show="showPicker1" destroy-on-close round position="bottom">
        <van-picker
            :model-value="pickerValue_jxpj"
            :columns="jxpj_list"
            @cancel="showPicker1 = false"
            @confirm="onConfirm_jxpj"
        />
      </van-popup>
      <!--课堂纪律-->
      <van-field
          v-model="ktjl"
          is-link
          readonly
          required
          label="课堂纪律"
          placeholder="选择等级"
          @click="showPicker2 = true"
          style="margin-top: 15px"
      />
      <van-popup v-model:show="showPicker2" destroy-on-close round position="bottom">
        <van-picker
            :model-value="pickerValue_ktjl"
            :columns="ktjl_list"
            @cancel="showPicker2 = false"
            @confirm="onConfirm_ktjl"
        />
      </van-popup>
      <!--备注反馈，具有统一模版-->
      <van-cell-group>
        <van-field
            type="textarea"
            v-model="jxpj_wt"
            label="教学内容清晰度说明"
            placeholder="具体情况说明(教室编号-课程名称-任课老师：教学内容清晰度说明。)："
            rows="4"
            autosize
            maxlength="68"
            show-word-limit
            style="margin-top: 15px"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
            type="textarea"
            v-model="ktjl_wt"
            label="课堂纪律说明"
            placeholder="具体情况说明(教室编号-课程名称-任课老师：客厅纪律情况说明。)："
            rows="4"
            autosize
            maxlength="68"
            show-word-limit
        />
      </van-cell-group>

      <div class="upload-section">
        <div class="upload-title">上传图片</div>
        <van-uploader
            v-model="photoList"
            multiple
            :max-count="5"
            :after-read="afterRead"
            class="uploader"
        >
          <template #preview-cover="{ file }">
            <div class="preview-cover">
              {{ photoList.name }}
            </div>
          </template>
        </van-uploader>
      </div>
    </div>
    <div class="dowm_bt">
      <van-button class="zsbc" @click="xq_zsbc">暂时保存</van-button>
      <van-button class="ljtj" @click="xq_submit">立即提交</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { computed, ref, onMounted } from "vue"
import router from "../../../Router"
import type { Numeric } from "vant/es/utils"
import axios from 'axios'
import { useUserStore } from '../../../Store/modules/userinfo/UserInfo.ts'
import { listClassesByCounselorUsingGet } from "../../../Api/banjimokuai.ts"
import { xunkelinshiStore } from "../../../Store/modules/xunkelinshi.ts"
import {showConfirmDialog, showFailToast, showSuccessToast} from "vant"
import {addPatrolClassUsingPost} from "../../../Api/xunkemokuai.ts";
import type {ClassInfo} from "../../../Store/types/ClassInfo";
import {uploadUsingPost} from "../../../Api/wenjianshangchuanmokuai.ts";

const userInfo = useUserStore()
const xunke = xunkelinshiStore()
const route = useRoute()

// 表单数据
const jxpj_wt = ref("")
const ktjl_wt = ref("")
const photoList = ref<Array<{file?: File, content?: string, name?: string}>>([])

// 教学评价相关
const jxpj_list = [
  { text: '清晰', value: 3 },
  { text: '较清晰', value: 2 },
  { text: '不清晰', value: 1 },
]
const jxpj = ref('')
const showPicker1 = ref(false)
const pickerValue_jxpj = ref<Numeric[]>([])

// 课堂纪律相关
const ktjl_list = [
  { text: '良好', value: 3 },
  { text: '一般', value: 2 },
  { text: '较差', value: 1 },
]
const ktjl = ref('')
const showPicker2 = ref(false)
const pickerValue_ktjl = ref<Numeric[]>([])

// 班级相关
const classList = ref<ClassInfo[]>([])
const showClassPicker = ref(false)
const selectedClass = ref<ClassInfo | null>(null)
// 状态
const submitting = ref(false)
const saving = ref(false)

// 日期时间相关
const currentDate = ref(['2025', '04', '05'])
const minDate = new Date(2020, 0, 1)
const maxDate = new Date(2099, 12, 31)
const date_value = ref('')
const showPicker3 = ref(false)

const time_value = ref('')
const showPicker4 = ref(false)
const currentTime = ref(['12', '00'])

// 计算属性
const title = computed(() => route.meta.title || '未知页面')
const selectedClassDisplay = computed(() => {
  if (!selectedClass.value) return ''
  return `${selectedClass.value.major} ${selectedClass.value.className}`
})

const classColumns = computed(() => {
  return classList.value.map(cls => ({
    text: `${cls.major} ${cls.className}`,
    value: cls.classId,
    classInfo: cls
  }))
})

// 方法
const formatter = (type: string, option: any) => {
  if (type === 'hour') option.text += '时'
  if (type === 'minute') option.text += '分'
  return option
}

const setCurrentDate = () => {
  const now = new Date()
  currentDate.value = [
    String(now.getFullYear()),
    String(now.getMonth() + 1).padStart(2, '0'),
    String(now.getDate()).padStart(2, '0')
  ]
}

const setCurrentTime = () => {
  const now = new Date()
  currentTime.value = [
    String(now.getHours()).padStart(2, '0'),
    String(now.getMinutes()).padStart(2, '0')
  ]
}

// 获取班级数据
async function getClass() {
  try {
    const response = await listClassesByCounselorUsingGet({
      counselorId: userInfo.userInfo.userId
    })
    classList.value = response.data.data
  } catch (err) {
    console.error('获取班级列表失败:', err)
    showFailToast('获取班级列表失败')
  }
}

// 加载保存的数据
const loadSavedData = () => {
  const saved = xunke.tempPatrolData

  if (saved.selectedClass) {
    // 从存储恢复时，需要找到对应的班级对象
    const matchedClass = classList.value.find(
        cls => cls.classId === saved.selectedClass?.classId
    )
    if (matchedClass) selectedClass.value = matchedClass
  }

  if (saved.date) date_value.value = saved.date
  if (saved.time) time_value.value = saved.time
  if (saved.jxpj) jxpj.value = saved.jxpj
  if (saved.jxpjValue) pickerValue_jxpj.value = [saved.jxpjValue]
  if (saved.ktjl) ktjl.value = saved.ktjl
  if (saved.ktjlValue) pickerValue_ktjl.value = [saved.ktjlValue]
  if (saved.jxpj_wt) jxpj_wt.value = saved.jxpj_wt
  if (saved.ktjl_wt) ktjl_wt.value = saved.ktjl_wt
  // if (saved.photoList) photoList.value = saved.photoList.map(p => ({
  //   name: p.name,
  //   url: p.url,
  //   content: p.url
  // }))
}

// 保存到Pinia
const saveToPinia = () => {
  const dataToSave = {
    selectedClass: selectedClass.value ? {
      classId: selectedClass.value.classId,
      className: selectedClass.value.className,
      grade: selectedClass.value.grade,
      major: selectedClass.value.major,
      college: selectedClass.value.college
    } : null,
    date: date_value.value,
    time: time_value.value,
    jxpj: jxpj.value,
    jxpjValue: pickerValue_jxpj.value?.[0] as number,
    ktjl: ktjl.value,
    ktjlValue: pickerValue_ktjl.value?.[0] as number,
    jxpj_wt: jxpj_wt.value,
    ktjl_wt: ktjl_wt.value,
    photoList: photoList.value.map(p => ({
      name: p.name || '',
      url: p.content || p.url || '',
      type: p.file?.type || ''
    }))
  }

  xunke.savePatrolData(dataToSave)
  showSuccessToast('记录已暂时保存')
}

// 选择器确认方法
const onConfirm_jxpj = ({ selectedValues, selectedOptions }: any) => {
  showPicker1.value = false
  pickerValue_jxpj.value = selectedValues
  jxpj.value = selectedOptions[0].text
}

const onConfirm_ktjl = ({ selectedValues, selectedOptions }: any) => {
  showPicker2.value = false
  pickerValue_ktjl.value = selectedValues
  ktjl.value = selectedOptions[0].text
}

const onConfirmClass = ({ selectedOptions }: any) => {
  showClassPicker.value = false
  selectedClass.value = selectedOptions[0].classInfo
}

const onConfirmDate = ({ selectedValues }: any) => {
  showPicker3.value = false
  date_value.value = `${selectedValues[0]}-${selectedValues[1]}-${selectedValues[2]}`
}

const onConfirmTime = ({ selectedValues }: any) => {
  showPicker4.value = false
  time_value.value = `${selectedValues[0]}:${selectedValues[1]}`
}

// 上传单个文件
const uploadFile = async (fileItem: { file?: File }, retries = 3) => {
  if (!fileItem.file) throw new Error('无效的文件')

  let lastError

  for (let i = 0; i < retries; i++) {
    try {
      const response = await uploadUsingPost({}, fileItem.file)

      if (response.data.code === 0 && response.data.data) {
        return response.data.data
      } else {
        lastError = new Error(response.data.message || '文件上传失败')
      }
    } catch (error) {
      lastError = error
    }

    if (i < retries - 1) {
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }

  throw lastError
}
// 文件上传处理
const afterRead = async (file: any) => {
  try {
    const files = Array.isArray(file) ? file : [file]

    for (const f of files) {
      // 显示上传状态
      f.status = 'uploading'
      f.message = '上传中...'

      // 检查文件大小
      if (f.file.size > 5 * 1024 * 1024) {
        throw new Error(`文件 ${f.file.name} 大小超过5MB限制`)
      }

      // 上传文件
      const url = await uploadFile(f)

      // 更新状态
      f.status = 'done'
      f.content = url
      f.message = '上传成功'
    }
  } catch (error) {
    file.status = 'failed'
    file.message = error.message || '上传失败'
    showFailToast(file.message)
  }
}
// 表单验证
const validateForm = () => {
  const errors: string[] = []

  if (!selectedClass.value) errors.push('请选择班级')
  if (!date_value.value) errors.push('请选择日期')
  if (!time_value.value) errors.push('请选择时间')
  if (!pickerValue_jxpj.value?.length) errors.push('请选择教学评价')
  if (!pickerValue_ktjl.value?.length) errors.push('请选择课堂纪律')
  if (!jxpj_wt.value) errors.push('请填写教学内容说明')
  if (!ktjl_wt.value) errors.push('请填写课堂纪律说明')

  return errors
}


// 提交表单
async function xq_submit() {
  // 验证表单
  const errors = validateForm()
  if (errors.length > 0) {
    showFailToast(errors[0])
    return
  }

  try {
    // 确认对话框
    await showConfirmDialog({
      title: '确认提交',
      message: '确定要提交本次巡查记录吗？'
    })

    submitting.value = true

    // 1. 上传文件（如果有）
    let photoPath = ''
    if (photoList.value.length > 0) {
      showSuccessToast('正在上传文件...')
      const uploadedFiles = await Promise.all(
          photoList.value
              .filter(file => file.file && !file.content)
              .map(file => uploadFile(file))
      )

      // 使用第一个上传的文件URL
      if (uploadedFiles.length > 0) {
        photoPath = uploadedFiles[0]
      } else if (photoList.value[0]?.content) {
        // 如果已经有URL（之前上传过的）
        photoPath = photoList.value[0].content
      }
    }

    // 2. 准备提交数据
    const submitData = {
      classId: selectedClass.value!.classId,
      contentClarity: pickerValue_jxpj.value![0] as number,
      counselorId: userInfo.userInfo.userId,
      interactionStatus: pickerValue_ktjl.value![0] as number,
      otherEvaluation: `教学内容清晰度说明:${jxpj_wt.value}\n课堂纪律说明:${ktjl_wt.value}`,
      photoPath: photoPath,
      roundTime: `${date_value.value}T${time_value.value}:00`
    }
    console.log(photoPath)

    // 3. 提交表单
    showSuccessToast('正在提交数据...')
    const response = await addPatrolClassUsingPost(submitData)

    console.log(response)
    if (response.data.code === 0) {
      // 清除临时数据
      xunke.clearTempData()
      setTimeout(() => {
        showSuccessToast('提交成功！')
      })
      router.push('/cqust/index')
    } else {
      throw new Error(response.data.message || '提交失败')
    }
  } catch (error: any) {
    if (error.message !== 'cancel') {
      console.error('提交失败:', error)
      showFailToast(error.message || '提交过程中出错')
    }
  } finally {
    submitting.value = false
  }
}

// 暂时保存
const xq_zsbc = () => {
  saveToPinia()
}

// 初始化
onMounted(() => {
  getClass().then(() => {
    loadSavedData()
  })
})
</script>

<style scoped>
.achievement-container {
  height: 100vh; /* 根据需要设置固定高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding: 10px; /* 内边距 */
}
.user-card {
  display: flex;
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  border: 2px solid #f0f0f0;
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  flex: 1;
  margin-left: 20px;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
}

.info-label {
  color: #888;
  width: 60px;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}
.add_xq{
  width: 100%;
  margin: 12px auto;
  border-radius: 15px;
  background-color: #fbfbfc;
}
.dowm_bt{
  width: 90%;
  overflow: hidden;
  margin: 20px auto;
}
.zsbc{
  width: 40%;
  background-color: white;
  border-radius: 20px;
  float: left;
}
.ljtj{
  width: 40%;
  background-color: rebeccapurple;
  border-radius: 20px;
  float: right;
  color: white;
}
.xzq {
  width: 100%;
  overflow: hidden;
}
.xzq_left {
  width: 47%;
  float: left;
}
.xzq_right {
  width: 47%;
  float: right;
}
.upload-section {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
}

.upload-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.uploader {
  margin-top: 8px;
}
</style>